package com.eight.cloud.upgrade.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.eight.cloud.openfeign.admin.api.SystemClient;
import com.eight.cloud.openfeign.admin.vo.permission.PermissionTree;
import com.eight.cloud.upgrade.constant.PermissionModuleEnum;
import com.eight.cloud.upgrade.service.IPermissionUpgradeService;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;

/**
 * @ClassName: PermissionUpgradeServiceImpl
 * @Author: TXC
 * @Date: 2025-02-14 15:53
 **/
@Service
public class PermissionUpgradeServiceImpl implements IPermissionUpgradeService {
    @Resource
    private SystemClient systemClient;
    @Override
    public void flushPermission(String module) {
        PermissionModuleEnum permissionModuleEnum = PermissionModuleEnum.getByValue(module);
        if (ObjectUtil.isNotNull(permissionModuleEnum)) {
            systemClient.flushPermission(initPermission(permissionModuleEnum));
        }else {
            throw new RuntimeException("模块不存在");
        }
    }

    @Override
    public void initSystem() {
        systemClient.initSystem();
        for (PermissionModuleEnum module : PermissionModuleEnum.values()) {
            systemClient.flushPermission(initPermission(module));
        }
    }

    public PermissionTree initPermission(PermissionModuleEnum module) {
        try {
            URL url = getClass().getClassLoader().getResource("permission/" + module.getValue() + ".yml");
            if (ObjectUtil.isNotNull(url)) {
                Yaml yaml = new Yaml();
                return yaml.loadAs(url.openStream(), PermissionTree.class);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
